package com.example.demo.service.impl

import com.example.demo.dao.TDoctorDao
import com.example.demo.dao.TNurseDao
import com.example.demo.dao.TNurseLevelDao
import com.example.demo.dao.TPatientDao
import com.example.demo.dao.Tables.tPatients
import com.example.demo.service.BoardService
import com.example.demo.service.DoorService
import com.example.demo.utils.CommUtils
import com.example.demo.utils.GmrDatabase
import com.example.demo.utils.WebDatabase
import com.example.demo.vo.DoctorVo
import com.example.demo.vo.DoorPatientListVo
import com.example.demo.vo.NurseVo
import com.example.demo.vo.PatientVo
import com.example.demo.vo.board.NurseLevelVo
import me.liuwj.ktorm.dsl.*
import me.liuwj.ktorm.entity.filter
import me.liuwj.ktorm.entity.toList
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import kotlin.collections.forEach


@Service
class DoorServiceImpl(
        @Autowired
        private val webDatabase: WebDatabase,
        @Autowired
        private val gmrDatabase: GmrDatabase
) : DoorService {

    override fun getDoorPatientList(roomCode: String): DoorPatientListVo? {
//        gmrDatabase.getDataBase().tPatients.filter {
//            it.room_code eq roomCode
//        }.toList().let {
//            val doorPatientListVo =  DoorPatientListVo()
//            val patients = PatientVo().getListVo(it)
//            val fix =  CommUtils.averageAssignFixLength(patients,3)
//            doorPatientListVo.list = fix
//            return doorPatientListVo
//        }
        val patientVoList = mutableListOf<PatientVo>()
        var nurseLevelVo: NurseLevelVo? = null
        var doctorVo: DoctorVo? = null
        var nurseVo: NurseVo? = null
        val doorPatientListVo =  DoorPatientListVo()
        gmrDatabase.getDataBase().from(TPatientDao)
                .leftJoin(TNurseLevelDao, on = TPatientDao.nurse_level_code eq TNurseLevelDao.level_code)
                .leftJoin(TDoctorDao, on = TPatientDao.doctor_code eq TDoctorDao.code)
                .leftJoin(TNurseDao, on = TPatientDao.nurse_code eq TNurseDao.code)
                .select()
                .where { TPatientDao.room_code eq roomCode }
                .forEach {
                    val patientVo = PatientVo().getVo(it)
                    nurseLevelVo = NurseLevelVo().getVoQuery(it)
                    doctorVo = DoctorVo().getDoctorVo(it)
                    nurseVo = NurseVo().getDoctorVo(it)
                    patientVo.nurseLevel = nurseLevelVo
                    patientVo.doctorVo = doctorVo
                    patientVo.nurseVo = nurseVo
                    patientVoList.add(patientVo)
                }
        val fix =  CommUtils.averageAssignFixLength(patientVoList,3)
        doorPatientListVo.list = fix
        return doorPatientListVo
    }





}